<?php

namespace frontend\models;

use common\models\BaseModel;
use common\models\PostModel;
use common\models\RelationPostTagsModel;
use Yii;
use yii\db\Query;
use yii\web\NotFoundHttpException;

class PostForm extends BaseModel
{

    public $id;
    public $title;
    public $content;
    public $label_img;
    public $tags;
    public $cat_id;
    public $_lastError = "";

    // 定义事件
    const SCENARIOS_CREATE = 'create';
    const SCENARIOS_UPDATE = 'update';
    
    // 场景设置
    const EVENT_AFTER_CREATE = 'eventAfterCreate';
    const EVENT_AFTER_UPDATE = 'eventAfterUpdate';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'posts';
    }

    // 场景设置
    public function scenarios()
    {
        $scenarios=[
            self::SCENARIOS_CREATE=>['title','content','label_img','cat_id','tags'],
            self::SCENARIOS_UPDATE=>['title','content','label_img','cat_id','tags'],
        ];
        return array_merge(parent::scenarios(),$scenarios);
    }

    // 定义规则
    public function rules()
    {

        return [
            [['id','title','content','cat_id'],'required'],
            [['id','cat_id'],'integer'],
            ['title','string','min' => 4,'max' => 50],
        ];

    }

    // 定义属性名称
    public function attributeLabels()
    {
        return [
            'id' => '编码',
            'title' => '标题',
            'content' => '内容',
            'label_img' => '标签图',
            'tags' => '标签',
            'cat_id' => '分类',
        ];
    }

    public  static function getList($cond,$curPage = 1,$pageSize = 5,$orderBy = ['id' =>SORT_DESC])
    {
        $model = new PostModel();
        $select = ['id','title','summary','label_img','cat_id','user_id','user_name','is_valid','created_at','updated_at'];
        $query = $model->find()->select($select)->where($cond)->with('relate.tag','extend')->orderBy($orderBy);
        // 获取分页数据
        $res = $model->getPages($query,$curPage,$pageSize);
        // 格式化
        $res['data'] = self::formatList($res['data']);
        return $res;
    }

    public static function formatList($data)
    {
        foreach($data as &$list){
            $list['tags'] = [];
            if(isset($list['relate']) && !empty($list['relate'])){
                foreach($list['relate'] as $lt){
                    $list['tags'][] = $lt['tag']['tag_name'];
                }
            }
            unset($list['relate']);
        }
        return $data;
    }

    // 创建文章
    public function create()
    {
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $model = new PostModel();
            $model->setAttributes($this->attributes);
            $model->summary = $this->getSummary();
            $model->user_id = Yii::$app->user->identity->id;
            $model->user_name = Yii::$app->user->identity->username;
            $model->is_valid = PostModel::IS_VALID;
            $model->created_at = time();
            $model->updated_at = time();
            if(!$model->save()){
                throw new \Exception('文章保存失败!');
            }
            $this->id = $model->id;
            // 调用其他事件
            $data = array_merge($this->getAttributes(),$model->getAttributes());
            $data['tags'] = $_POST['PostForm']['tags'];
            $this->eventAfterCreate($data);
            $transaction->commit();
            return true;
        }catch(\Exception $e){
            $transaction->rollBack();
            $this->_lastError = $e->getMessage();
            return false;
        }
    }

    // 获取文章数据
    public function getViewById($id)
    {
        $res = PostModel::find()->with('relate.tag','extend')->where(['id' => $id])->asArray()->one();
        if(!$res){
            throw new NotFoundHttpException('文章不存在!');
        }
        if(isset($res['relate']) && !empty($res['relate'])){
            foreach($res['relate'] as $list){
                $res['tags'][] = $list['tag']['tag_name'];
            }
        }
        unset($res['relate']);
        return $res;
    }

    private function getSummary($s= 0,$e = 90,$char = 'utf-8')
    {
        if(empty($this->content)){
            return null;
        }
        return (mb_substr(str_replace('&nbsp;','',strip_tags($this->content)),$s,$e,$char));
    }

    private function eventAfterCreate($data)
    {
        $this->on(self::EVENT_AFTER_CREATE,[$this, 'eventAddTag'],$data);
        $this->trigger(self::EVENT_AFTER_CREATE);
    }

    public function eventAddTag($event)
    {
        $tag = new TagForm();
        $tag->tags = $event->data['tags'];
        $tagids = $tag->saveTags();
        // 删除原来的关系
        RelationPostTagsModel::deleteAll(['post_id' => $event->data['id']]);
        if(!empty($tagids)){
            foreach($tagids as $k => $id){
                $row[$k]['post_id'] = $this->id;
                $row[$k]['tag_id'] = $id;
            }
            $res = (new Query())->createCommand()
            ->batchInsert(RelationPostTagsModel::tableName(),['post_id','tag_id'],$row)
            ->execute();
            if(!$res){
                throw new \Exception("关联关系保存失败");
            }
        }
    }

}